<?php
//通过继承 CI_Model 创建了一个新模型
class News_Model extends CI_Model
{

    protected $table_name = 'news';

    protected $allowedFields = ['title','text'];

    //加载了数据库类,数据库类可以通过 $this->db 对象访问
    public function __construct()
    {
        $this->load->database();
    }

    public function get_news($slug = FALSE)
    {
        if ($slug === FALSE)
        {
            $query = $this->db->get('news');
            return $query->result_array();
        }

        $query = $this->db->get_where('news', array('id' => $slug));
        return $query->row_array();
    }

    //过滤字段
    protected function filter_field($data)
    {
        $fields = $this->db->list_fields($this->table_name);//获取数据库字段
        foreach($data as $key=>$val){
            if(!in_array($key,$fields)){
                unset($data[$key]);
            }
        }
        return $data;
    }

    //添加
    public function add($data)
    {
        $data = $this->filter_field($data);
        $res = $this->db->insert($this->table_name,$data);
        if($res){
            return $this->db->insert_id();
        }else{
            return false;
        }
    }

//     //删除
//     public function delete($id)
//     {
//         return $this->db->delete('user', array('id' => $id));
//     }

//     //点及改
//     public function status($id,$username,$password)
//     {
//         $query = $this->db->where(array('id'=>$id))->update('user',array('username'=>$username,'password'=>$password));
//         return $query;

//     }

//     //获取总条数
//     public function count()
//     {
//         return $this->db->count_all_results($this->table_name);
//     }

//     //查看
//     public function select($offset)
//     {//读取配置每页显示条数
//         return $this->db->get($this->table_name,$this->config->item('page_size'),$offset)->result_array();
//     }

//     //查询所有结果
//     public function getAll()
//     {
//         return $this->db->get($this->table_name)->result_array();
//     }
//   
    //查询单条
    public function getOne($id)
    {
        return $this->db->where(array('id'=>$id))->get($this->table_name)->row_array();
    }
}